package com.xujianlun.cpms.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.config.AuthAccess;
import com.xujianlun.cpms.entity.sys.User;
import com.xujianlun.cpms.service.sys.IUserService;
import com.xujianlun.cpms.utils.TokenUtil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujianlun.cpms.common.Response;
import com.xujianlun.cpms.service.INoticeService;
import com.xujianlun.cpms.entity.Notice;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 公告管理 前端控制器
 * </p>
 *
 * @author xujianlun
 * @since 2022-12-18
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Resource
    private INoticeService noticeService;
    private final String now = DateUtil.now();
    @Resource
    private IUserService userService;
    // 新增或者更新
    @PostMapping
    public Response save(@RequestBody Notice notice) {
        if (notice.getId() == null) {
            Integer userId = TokenUtil.getTokenUserId();
            User user = userService.getById(userId);
            notice.setTime(DateUtil.now());
            notice.setUser(user.getNickName());
        }
        noticeService.saveOrUpdate(notice);
        return Response.success();
    }


    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        noticeService.removeById(id);
        return Response.success();
    }

    @PostMapping("/del/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        noticeService.removeByIds(ids);
        return Response.success();
    }
    @AuthAccess
    @GetMapping
    public Response findAll() {
        return Response.success(noticeService.list());
    }
    @AuthAccess
    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        return Response.success(noticeService.getById(id));
    }

    @GetMapping("/page")
    public Response findPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)){
            queryWrapper.like("name",name);
        }
        queryWrapper.eq("num",0);
        queryWrapper.orderByDesc("id");
        return Response.success(noticeService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

